const Express = require("express");
const RecordServer = require("../../servers/RecordInfo");
const ResponseHelper = require("../ResponseHelper");
const router = Express.Router();
const {mkdir2} = require("../../tools");
const fs = require("fs");
const os = require("os");
const {createReadStream, createWriteStream} = require('fs');

//type imgs videos both
router.post("/", async (req, res, next) => {
    try {
        
        const recordInfo = await RecordServer.getByIdAndPatient(req.body.id);
        const type = req.body.type;
        const name = getName(recordInfo);


        const system = os.platform();
        let uploadStaticPath = `C:\\imgsData\\${name}`;
        let readPath = 'C:\\uploads'
        if (system === "linux") {
            uploadStaticPath = `/home/cobot/imgsData/${name}`;
            readPath = `/home/cobot/uploads`;
            await mkdir2(uploadStaticPath);
        } else {
            await mkdir2(uploadStaticPath);
        }

        if (type === "imgs") {
            const reportimg = JSON.parse(recordInfo.reportimg);
            const promises = reportimg.map(async (item,index) => {
                const urlArrs = item.url.split('/');
                const imgsName = urlArrs[urlArrs.length - 1];
                const oriPath = os.platform() === 'linux' ? `${readPath}/${imgsName}` : `${readPath}\\${imgsName}`;
                const targetName = getImageName(recordInfo,index+1);
                await readAndWriteFile(oriPath, `${uploadStaticPath}/${targetName}.bmp`)
            });
            await Promise.all(promises);
            ResponseHelper.sendData("写入完成！", res);
        } else if (type === "videos") {
            const videos = JSON.parse(recordInfo.videos);
            const promises = videos.map(async (item) => {
                const urlArrs = item.url.split('/');
                const videoName = urlArrs[urlArrs.length - 1];
                const oriPath = os.platform() === 'linux' ? `${readPath}/${videoName}` : `${readPath}\\${videoName}`;
                await readAndWriteFile(oriPath, `${uploadStaticPath}/${videoName}.mp4`)
            });
            await Promise.all(promises);
            ResponseHelper.sendData("写入完成！", res);
        } else if (type === "both") {
            
            const reportimg = JSON.parse(recordInfo.reportimg);
            const promises = reportimg.map(async (item,index) => {
                const urlArrs = item.url.split('/');
                const imgsName = urlArrs[urlArrs.length - 1];
                const oriPath = os.platform() === 'linux' ? `${readPath}/${imgsName}` : `${readPath}\\${imgsName}`;
                const targetName = getImageName(recordInfo,index+1);
                await readAndWriteFile(oriPath, `${uploadStaticPath}/${targetName}.bmp`)
            });
            await Promise.all(promises);
            const videos = JSON.parse(recordInfo.videos);
            const promises2 = videos.map(async (item) => {
                const urlArrs = item.url.split('/');
                const videoName = urlArrs[urlArrs.length - 1];
                const oriPath = os.platform() === 'linux' ? `${readPath}/${videoName}` : `${readPath}\\${videoName}`;
                await readAndWriteFile(oriPath, `${uploadStaticPath}/${videoName}.mp4`)
            });
            await Promise.all(promises2);

            ResponseHelper.sendData("写入完成！", res);
        }
    } catch (err) {
        ResponseHelper.sendData(err, res);
    }
});

function writeImgs(originPath, data, name, index) {
    return new Promise((resolve, reject) => {
        var path = `${originPath}\\${name}_${index}.jpg`; //
        var base64 = data.replace(/^data:image\/\w+;base64,/, ""); //去掉图片base64码前面部分data:image/png;base64
        var dataBuffer = new Buffer(base64, "base64"); //把base64码转成buffer对象，
        fs.writeFile(path, dataBuffer, function (err) {
            //用fs写入文件
            if (err) {
                console.log(err);
                reject(err);
            } else {
                console.log("Write successful!");
                resolve("Write successful!");
            }
        });
    });
}
/**
 * 文件读写
 * @param {*} originPath 原始地址
 * @param {*} targetPath 目标
 * @returns 
 */
function readAndWriteFile(originPath, targetPath) {
    return new Promise((resolve, reject) => {
        const rs = createReadStream(originPath);
        const ws = createWriteStream(targetPath);
        rs.on('data', (chunk) => {
            ws.write(chunk)
        });
        rs.on('end', (chunk) => {
            ws.end(chunk);
            resolve('Write end')
        });
    });
}


function getName(record){
   const typeInfo = {
        '腹部':'ABD',
        '小器官':'SMP',
        '血管':'VAS',
        '泌尿':'URO'
   };
   const pos = record.pos;
   let fileName;
   if(pos&&typeInfo[pos]){
       fileName = typeInfo[pos]
   }else{
       fileName = 'XXX'
   };
   return `${record.patientinfo.name}CO${fileName}-${record.id}`;
}

function getImageName(record,index){
    try{
        const typeInfo = {
            '腹部':'ABD',
            '小器官':'SMP',
            '血管':'VAS',
            '泌尿':'URO'
       };
       const pos = record.pos;
       let fileName;
       if(pos&&typeInfo[pos]){
           fileName = typeInfo[pos]
       }else{
           fileName = 'XXX'
       };
       return `${record.id}_${fileName}${index}`;
    }catch(err){
       console.log(err)
    }

}


module.exports = router;
